package com.lanou3g.zjl.chating.home.setting;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.util.EMLog;
import com.lanou3g.zjl.chating.R;
import com.lanou3g.zjl.chating.base.BaseActivity;
import com.lanou3g.zjl.chating.home.personal_center.CircleImageView;
import com.lanou3g.zjl.chating.utils.GetUserAvatarHelper;
import com.lanou3g.zjl.chating.utils.ProgressLayout;
import com.lanou3g.zjl.chating.volley.VolleySingleton;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;

import java.io.ByteArrayOutputStream;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by dllo on 15/11/30.
 */
public class PersonCenterActivity extends BaseActivity {
    @Bind(R.id.userPic)
    CircleImageView avatarPic;
    @Bind(R.id.setUserName)
    TextView setUserName;
    private VolleySingleton singleton;
    private SharedPreferences userAvatar;//存储用户头像地址
    private SharedPreferences.Editor editAvtar;
    private GetUserAvatarHelper helper;
    @Bind(R.id.progress_layout)
    ProgressLayout progressLayout;
    @Override
    protected int getLayout() {

        return R.layout.activity_personcenter;
    }

    @Override
    protected void initData() {

        userAvatar = getSharedPreferences("UserAvatar", Context.MODE_PRIVATE);
        editAvtar = userAvatar.edit();
        setUserName.setText(EMChatManager.getInstance().getCurrentUser());
        singleton = VolleySingleton.getInstance(this);
//        if(!userAvatar.getString(EMChatManager.getInstance().getCurrentUser(), "").equals(""))
//        singleton.getPic(userAvatar.getString(EMChatManager.getInstance().getCurrentUser(), ""), avatarPic);
        helper = new GetUserAvatarHelper(PersonCenterActivity.this,avatarPic,EMChatManager.getInstance().getCurrentUser());
        helper.execute(EMChatManager.getInstance().getCurrentUser());
    }

    //点击头像之后跳转到图库挑选图片
    @OnClick(R.id.userPic)
    void getUserPic() {
        //显示进度条
        progressLayout.showProgress();
        Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
        pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(pickIntent, 1);
    }
    //点击返回
    @OnClick(R.id.back) void clickBack(){

        finish();
    }
    //结果返回处理
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (data == null || data.getData() == null) {
                    progressLayout.showContent();
                    return;
                }
                startPhotoZoom(data.getData());
                break;
            case 2:
                if (data != null) {
                    setPicToView(data);
                }else {
                    progressLayout.showContent();
                }
                break;
        }
    }

    //对所选图片继续截取
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, 2);
    }

    //将图片设置到控件中,并上传到Parse第三方库中
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(getResources(), photo);
            uploadUserAvatar(Bitmap2Bytes(photo));
            avatarPic.setImageDrawable(drawable);
        }

    }

    //图片上传结果监听
    private void uploadUserAvatar(final byte[] data) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                final String avatarUrl = uploadParseAvatar(data);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (avatarUrl != null) {
                            //将头像地址保存起来
                            editAvtar.putString(EMChatManager.getInstance().getCurrentUser(), avatarUrl);
                            editAvtar.commit();
                            Log.i("PersonCenterActivity", avatarUrl);
                            Toast.makeText(PersonCenterActivity.this, "头像设置成功", Toast.LENGTH_SHORT).show();
                            progressLayout.showContent();
                        } else {
                            Toast.makeText(PersonCenterActivity.this, "头像设置失败", Toast.LENGTH_SHORT).show();
                        }

                    }
                });

            }
        }).start();
    }

    //将图片装换为byte类型
    public byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    //上传图片到Parse库的方法
    public String uploadParseAvatar(byte[] data) {
        String username = EMChatManager.getInstance().getCurrentUser();
        ParseQuery<ParseObject> pQuery = ParseQuery.getQuery("UserSet");
        pQuery.whereEqualTo("username", username);
        ParseObject pUser = null;
        try {
            pUser = pQuery.getFirst();
            if (pUser == null) {
                pUser = new ParseObject("UserSet");
                pUser.put("username", username);
            }
            ParseFile pFile = new ParseFile(data);
            pUser.put("avatar", pFile);
            pUser.save();
            return pFile.getUrl();
        } catch (ParseException e) {
            if (e.getCode() == ParseException.OBJECT_NOT_FOUND) {
                try {
                    pUser = new ParseObject("UserSet");
                    pUser.put("username", username);
                    ParseFile pFile = new ParseFile(data);
                    pUser.put("avatar", pFile);
                    pUser.save();
                    return pFile.getUrl();
                } catch (ParseException e1) {
                    e1.printStackTrace();
                    Log.e("PersonCenterActivity", "parse error " + e1.getMessage());
                }
            } else {
                e.printStackTrace();
                Log.e("PersonCenterActivity", "parse error " + e.getMessage());
            }
        }
        return null;
    }
}
